//
//  AKMediaViewController.m
//  CocoaBean
//
//  Created by sleeper on 5/31/10.
//  Copyright 2010 __MyCompany__, Inc. All rights reserved.
//

#import "AKRequestHeader.h"
#import "AKAppController.h"
#import "AKMediaEntry.h"

#import "AKMediaViewController.h"

NSString * const _kMediaSeparator = @" / ";

enum {
	_kBookRowTitle = 0,
	_kBookRowTranslator,
	_kBookRowAuthor,
	_kBookRowISBN,
	_kBookRowPages,
	_kBookRowPrice,
	_kBookRowPublisher,
	_kBookRowBinding,
	_kBookRowPublishDate,
		
	_kBookRowSummary,
	_kBookRowAuthorIntro,
	_kBookRowCount
};

enum {
	_kMusicTitle = 0,
	_kMusicAka,
	_kMusicSingers,
	_kMusicNumDiscs,
	_kMusicEAN,
	_kMusicPublishDate,
	_kMusicVersion,
	_kMusicPublisher,
	_kMusicMedia,
	
	_kMusicSummary,
	_kMusicTracks,
	_kMusicRowCount
};

enum {
	_kMovieTitle = 0,
	_kMovieWriter,
	_kMovieDirector,
	_kMovieCasts,
	_kMovieCountry,
	_kMovieSite,
	_kMoviePublishDate,
	_kMovieLanguage,
	_kMovieAka,
	_kMovieIMDB,
	
	_kMovieSummary,
	_kMovieRowCount
};

@interface AKMediaViewController () <AKRequestDelegate>
@property (nonatomic, retain) AKMediaEntry *mediaEntry;
@end

@implementation AKMediaViewController

@synthesize mediaIDField, isbnSwitch, tableView;
@synthesize segmentedControl;
@synthesize mediaEntry = _mediaEntry;

- (id)init
{
	if ((self = [super initWithNibName:@"AKMediaViewController" bundle:nil])) {
		self.title = NSLocalizedString(@"Book, Music, Movie", @"Media");
	}
	return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
	
	self.navigationItem.titleView = segmentedControl;
	
	UIBarButtonItem *goButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Go", @"Go")
																 style:UIBarButtonItemStyleBordered target:self action:@selector(go)];
	self.navigationItem.rightBarButtonItem = goButton;
	AK_RELEASE(goButton);
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
	NSInteger retVal = 0;
	if (_mediaEntry != nil) {
		switch (_mediaEntry.category) {
			case AKEntryCategoryBook:
				retVal = _kBookRowCount;
				break;
			case AKEntryCategoryMusic:
				retVal = _kMusicRowCount;
				break;
			case AKEntryCategoryMovie:
				retVal = _kMovieRowCount;
				break;
		}
	}
	return retVal;
}

- (void)_getCellDetailString:(NSString **)outDetailString labelString:(NSString **)outLabelString forBookAtIndexPath:(NSIndexPath *)indexPath
{
	NSString *labelString = nil;
	NSString *detailString = nil;
	switch (indexPath.row) {
		case _kBookRowTitle:
			labelString = NSLocalizedString(@"Title", @"Title");
			detailString = _mediaEntry.title;
			break;
		case _kBookRowTranslator:
			labelString = NSLocalizedString(@"Translator", @"Translator");
			detailString = AKStringForArrayOfStrings(_mediaEntry.translators, _kMediaSeparator);
			break;
		case _kBookRowAuthor:
			labelString = NSLocalizedString(@"Author", @"Author");
			detailString = AKStringForArrayOfStrings(_mediaEntry.bookAuthors, _kMediaSeparator);
			break;
		case _kBookRowISBN:
			labelString = NSLocalizedString(@"ISBN", @"ISBN");
			detailString = _mediaEntry.isbn13;
			break;
		case _kBookRowPages:
			labelString = NSLocalizedString(@"Pages", @"Pages");
			detailString = _mediaEntry.pages;
			break;
		case _kBookRowPrice:
			labelString = NSLocalizedString(@"Price", @"Price");
			detailString = _mediaEntry.price;
			break;
		case _kBookRowPublisher:
			labelString = NSLocalizedString(@"Publisher", @"Publisher");
			detailString = _mediaEntry.publisher;
			break;
		case _kBookRowBinding:
			labelString = NSLocalizedString(@"Binding", @"Binding");
			detailString = _mediaEntry.binding;
			break;
		case _kBookRowPublishDate:
			labelString = NSLocalizedString(@"Publish Date", @"Publish Date");
			detailString = _mediaEntry.publishDate;
			break;
		case _kBookRowSummary:
			labelString = NSLocalizedString(@"Summary", @"Summary");
			detailString = _mediaEntry.summary;
			break;
		case _kBookRowAuthorIntro:
			labelString = NSLocalizedString(@"Author Intro", @"Author Intro");
			detailString = _mediaEntry.authorIntro;
			break;
	}
	
	if (detailString != nil && outDetailString != NULL)
		*outDetailString = detailString;
	if (labelString != nil && outLabelString != NULL)
		*outLabelString = labelString;
}

- (void)_getCellDetailString:(NSString **)outDetailString labelString:(NSString **)outLabelString forMusicAtIndexPath:(NSIndexPath *)indexPath
{
	NSString *labelString = nil;
	NSString *detailString = nil;
	switch (indexPath.row) {
		case _kMusicTitle:
			labelString = NSLocalizedString(@"Title", @"Title");
			detailString = _mediaEntry.albumTitle;
			break;			
		case _kMusicAka:
			labelString = NSLocalizedString(@"Aka", @"AKA");
			detailString = AKStringForArrayOfStrings(_mediaEntry.akas, _kMediaSeparator);
			break;
		case _kMusicSingers:
			labelString = NSLocalizedString(@"Singers", @"Singers");
			detailString = AKStringForArrayOfStrings(_mediaEntry.singers, _kMediaSeparator);
			break;
		case _kMusicNumDiscs:
			labelString = NSLocalizedString(@"Number of Discs", @"Number of Discs");
			detailString = _mediaEntry.numberOfDiscs;
			break;
		case _kMusicEAN:
			labelString = NSLocalizedString(@"EAN", @"EAN");
			detailString = _mediaEntry.ean;
			break;
		case _kMusicPublishDate:
			labelString = NSLocalizedString(@"Publish Date", @"Publish Date");
			detailString = _mediaEntry.publishDate;
			break;
		case _kMusicVersion:
			labelString = NSLocalizedString(@"Version", @"Version");
			detailString = _mediaEntry.musicVersion;
			break;
		case _kMusicPublisher:
			labelString = NSLocalizedString(@"Puslisher", @"Publisher");
			detailString = _mediaEntry.publisher;
			break;
		case _kMusicMedia:
			labelString = NSLocalizedString(@"Media", @"Media");
			detailString = _mediaEntry.media;
			break;
		case _kMusicSummary:
			labelString = NSLocalizedString(@"Summary", @"Summary");
			detailString = _mediaEntry.summary;
			break;
		case _kMusicTracks:
			labelString = NSLocalizedString(@"Tracks", @"Tracks");
			detailString = AKStringForArrayOfStrings(_mediaEntry.tracks, @"\n");
			break;
	}
	
	if (detailString != nil && outDetailString != NULL)
		*outDetailString = detailString;
	if (labelString != nil && outLabelString != NULL)
		*outLabelString = labelString;
}

- (void)_getCellDetailString:(NSString **)outDetailString labelString:(NSString **)outLabelString forMovieAtIndexPath:(NSIndexPath *)indexPath
{
	NSString *labelString = nil;
	NSString *detailString = nil;
	switch (indexPath.row) {
		case _kMovieTitle:
			labelString = NSLocalizedString(@"Title", @"Title");
			detailString = _mediaEntry.title;
			break;
		case _kMovieWriter:
			labelString = NSLocalizedString(@"Writers", @"Writers");
			detailString = AKStringForArrayOfStrings(_mediaEntry.writers, _kMediaSeparator);
			break;
		case _kMovieDirector:
			labelString = NSLocalizedString(@"Director", @"Director");
			detailString = AKStringForArrayOfStrings(_mediaEntry.directors, _kMediaSeparator);
			break;
		case _kMovieCasts:
			labelString = NSLocalizedString(@"Casts", @"Casts");
			detailString = AKStringForArrayOfStrings(_mediaEntry.casts, _kMediaSeparator);
			break;
		case _kMovieCountry:
			labelString = NSLocalizedString(@"Country", @"Country");
			detailString = _mediaEntry.country;
			break;
		case _kMovieSite:
			labelString = NSLocalizedString(@"Site", @"Site");
			detailString = _mediaEntry.siteURL;
			break;
		case _kMoviePublishDate:
			labelString = NSLocalizedString(@"Publish Date", @"Publish Date");
			detailString = _mediaEntry.publishDate;
			break;
		case _kMovieLanguage:
			labelString = NSLocalizedString(@"Language", @"Language");
			detailString = _mediaEntry.language;
			break;
		case _kMovieAka:
			labelString = NSLocalizedString(@"AKAs", @"AKAs");
			detailString = AKStringForArrayOfStrings(_mediaEntry.akas, _kMediaSeparator);
			break;
		case _kMovieIMDB:
			labelString = NSLocalizedString(@"IMDB", @"IMDB");
			detailString = _mediaEntry.imdbURL;
			break;
		case _kMovieSummary:
			labelString = NSLocalizedString(@"Summary", @"Summary");
			detailString = _mediaEntry.summary;
			break;
	}
	
	if (detailString != nil && outDetailString != NULL)
		*outDetailString = detailString;
	if (labelString != nil && outLabelString != NULL)
		*outLabelString = labelString;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSString *identifier = @"CELL";
	
	UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:identifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:identifier] autorelease];
		cell.textLabel.numberOfLines = 0;
		cell.detailTextLabel.numberOfLines = 0;
	}
	
	NSString *labelString = @"";
	NSString *detailString = @"";
	switch (_mediaEntry.category) {
		case AKEntryCategoryBook:
			[self _getCellDetailString:&detailString labelString:&labelString forBookAtIndexPath:indexPath];
			break;
		case AKEntryCategoryMusic:
			[self _getCellDetailString:&detailString labelString:&labelString forMusicAtIndexPath:indexPath];
			break;
		case AKEntryCategoryMovie:
			[self _getCellDetailString:&detailString labelString:&labelString forMovieAtIndexPath:indexPath];
			break;
	}
	
	cell.textLabel.text = labelString;
	cell.detailTextLabel.text = detailString;
	
	return cell;
}

#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	CGFloat retVal = table.rowHeight;
	NSString *detailString = nil;
	switch (_mediaEntry.category) {
		case AKEntryCategoryBook:
			[self _getCellDetailString:&detailString labelString:NULL forBookAtIndexPath:indexPath];
			break;
		case AKEntryCategoryMusic:
			[self _getCellDetailString:&detailString labelString:NULL forMusicAtIndexPath:indexPath];
			break;
		case AKEntryCategoryMovie:
			[self _getCellDetailString:&detailString labelString:NULL forMovieAtIndexPath:indexPath];
			break;
	}
	
	if (detailString)
		retVal = MIN(1000.0, MAX(40.0, [detailString sizeWithFont:[UIFont boldSystemFontOfSize:15.0] constrainedToSize:CGSizeMake(207, CGFLOAT_MAX)].height + 10.0));
	
	return retVal;
}

#pragma mark Actions

- (IBAction)go
{
	NSString *type = nil;
	switch (segmentedControl.selectedSegmentIndex) {
		case 0:
			type = isbnSwitch.on ? kAKRequestTypeBookISBN : kAKRequestTypeBook;
			break;
		case 1:
			type = kAKRequestTypeMusic;
			break;
		case 2:
			type = kAKRequestTypeMovie;
			break;
	}
	if ([type length] > 0) {
		AKRequest *request = [AKRequest requestWithType:type extraInfo:mediaIDField.text];
		[[AKAppController sharedAppController].requestManager runRequest:request delegate:self];
	}
}

#pragma mark AKRequestDelegate methods

- (void)request:(AKRequest*)request didFinishWithData:(NSData *)data
{
	NSString *responseString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
	id responseInfo = [responseString JSONValue];
	
	if (responseInfo == nil) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"Error") message:responseString delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"OK") otherButtonTitles:nil];
		[alert show];
		AK_RELEASE(alert);
	}
	else {
		self.mediaEntry = [[[AKMediaEntry alloc] initWithDictionary:responseInfo] autorelease];
		
		[mediaIDField resignFirstResponder];
		[tableView reloadData];
	}
}

- (void)request:(AKRequest*)reqeust didFailWithError:(NSError*)error
{
}

#pragma mark -

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
	self.mediaIDField = nil;
	self.isbnSwitch = nil;
	self.tableView = nil;
	self.segmentedControl = nil;
}

- (void)dealloc
{
	[[AKAppController sharedAppController].requestManager removeDelegate:self];

	AK_RELEASE(mediaIDField);
	AK_RELEASE(isbnSwitch);
	AK_RELEASE(tableView);
	
	AK_RELEASE(_mediaEntry);
	
	AK_RELEASE(segmentedControl)

    [super dealloc];
}

@end
